<template>

  <li>
    <label>
      <input type="checkbox" :checked="todo.done" @change="change(todo.id)"/>

      <span v-show="!todo.isEdit">{{ todo.title }}</span>

      <input type="text"
             :value="todo.title"
             v-show="todo.isEdit"
             @blur="handleBlur(todo,$event)"
             ref="titRef"
      >
    </label>

    <button class="btn btn-danger" @click="deleteItem(todo.id)">删除</button>

    <button class="btn btn-edit" v-show="!todo.isEdit" @click="handleEdit(todo)">编辑</button>

  </li>
</template>

<script>
import pubsub from "pubsub-js";

export default {
  name: "MyItem",
  //声明接收对象
  props: ['todo'],
  mounted() {
    console.log('item', this.todo)
  },
  methods: {
    change(id) {
      console.log('item组件，我改变了：', id)
      //通知app组件将对应的todo.done值取反
      pubsub.publish('checkTodo', id)
    },
    deleteItem(id) {
      if (confirm('确定要删除吗？')) {
        pubsub.publish('deleteTodo', id)
      }
    },
    // 编辑功能
    handleEdit(todo) {
      if (!todo.hasOwnProperty('isEdit')) {
        console.log('todo没有isEdit')
        this.$set(todo, 'isEdit', true)
      } else {
        console.log('todo有isEdit了---')
        todo.isEdit = true
      }
      console.log('item组件，我编辑了：', todo)
      // this.$refs.titRef.focus()//无法聚焦
      /*setTimeout(() => {
        this.$refs.titRef.focus()
      },200)*/
      this.$nextTick(function (){

        this.$refs.titRef.focus()
      })
    },
    handleBlur(todo, e) {
      //失去焦点，保存数据
      todo.isEdit = false
      if (!e.target.value.trim()) {
        alert('输入不能为空')
        return
      }
      this.$bus.$emit('updateTodo', todo.id, e.target.value)
      console.log('updateTodo', todo.id, e.target.value)

    }
  }
}
</script>

<style scoped>

/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover button {
  display: block;
}

li:hover {
  background: #afa8a8;
}


</style>